package org.nf.shopping.controller.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.nf.shopping.common.exception.ErrorsEnum;
import org.nf.shopping.common.vo.ResultVO;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author czl
 * @Date 2024-12-02
 */
public class RoleControllerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if (session.getAttribute("role") != null){
            return true;
        }
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
            ResultVO vo = new ResultVO();
            vo.setCode(ErrorsEnum.AUTH_EXCEPTION.code());
            vo.setMessage(ErrorsEnum.AUTH_EXCEPTION.message());
            response.setContentType("Application/json;charset=utf-8");
            String json = new ObjectMapper().writeValueAsString(vo);
            response.getWriter().println(json);
        }else {
            response.sendRedirect("login.html");
        }
        return false;
    }
}
